# Multi-stage build for production optimization
FROM node:20-alpine as builder

# Install pnpm
RUN npm install -g pnpm@8

WORKDIR /app

# Copy package files for dependency installation
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY turbo.json ./
COPY tsconfig.base.json ./

# Copy all package.json files
COPY apps/*/package.json ./apps/*/
COPY packages/*/package.json ./packages/*/
COPY examples/plugins/*/package.json ./examples/plugins/*/

# Install dependencies
RUN pnpm install --frozen-lockfile

# Copy source code
COPY . .

# Build all packages and applications
RUN pnpm run build

# Production image
FROM node:20-alpine

# Install pnpm and curl for health checks
RUN npm install -g pnpm@8 && \
    apk add --no-cache curl

WORKDIR /app

# Create non-root user for security
RUN addgroup --system --gid 1001 baihu && \
    adduser --system --uid 1001 baihu

# Copy built applications and dependencies
COPY --from=builder --chown=baihu:baihu /app/apps/web/dist ./web
COPY --from=builder --chown=baihu:baihu /app/apps/server/dist ./server
COPY --from=builder --chown=baihu:baihu /app/examples ./examples
COPY --from=builder --chown=baihu:baihu /app/node_modules ./node_modules
COPY --from=builder --chown=baihu:baihu /app/packages ./packages

# Create data and plugins directories
RUN mkdir -p /app/data /app/logs && \
    chown -R baihu:baihu /app

# Switch to non-root user
USER baihu

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/api/health/simple || exit 1

# Set production environment
ENV NODE_ENV=production

# Start the server
CMD ["node", "server/index.js"]
